#include "chatwindow.h"
#include "ui_chatwindow.h"
#include <QtNetwork>
#include <QDir>
#include <QFileInfo>
#include <QStringList>
#include <QDateTime>
#include <QDebug>
#include <QTemporaryFile>
#include <QFile>
#include <QDataStream>
#include <QTextCodec>
#include "logindialog.h"
#include "loginwidget.h"
#include <QMessageBox>

ChatWindow::ChatWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ChatWindow)
{
    ui->setupUi(this);

    connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(pushButton_clicked()));

    qDebug()<<"ChatWindow:"+LoginDialog::NICKNAME;
    database = QSqlDatabase::addDatabase("QSQLITE");
    database.setDatabaseName("database.db");

    QSqlQuery chat_query;        //变量必须在成功打开数据库后定义才有效

    //打开数据库
    if(!database.open())
    {
        qDebug()<<database.lastError();
        qFatal("failed to connect.") ;
    }
    else
    {
        QString tempstring="select * from user where name='"+LoginDialog::NICKNAME+"'";
        qDebug()<<tempstring;
        if(!chat_query.exec(tempstring))
        {
            qDebug()<<chat_query.lastError();
            matchFlag=false;
        }
        else
        {
            while(chat_query.next())
            {
                usr_id = chat_query.value(0).toInt();
                usr_passwd = chat_query.value(1).toString();
                usr_name = chat_query.value(2).toString();
                usr_email = chat_query.value(3).toString();
                usr_history = chat_query.value(4).toInt();

                qDebug()<<QString("chatid=%1    passwd=%2     name=%3       email=%4    history=%5").arg(usr_id).arg(usr_passwd).arg(usr_name).arg(usr_email).arg(usr_history);
                port = 8000+usr_id;
            }
        }
        QString receiverId="select * from user where chatid="+QString("%1").arg(LoginWidget::ID)+"";
        qDebug()<<receiverId;
        if(!chat_query.exec(receiverId))
        {
            qDebug()<<chat_query.lastError();
            matchFlag=false;
        }
        else
        {
            while(chat_query.next())
            {
                usr_id = chat_query.value(0).toInt();
                usr_passwd = chat_query.value(1).toString();
                usr_name = chat_query.value(2).toString();
                usr_email = chat_query.value(3).toString();
                usr_history = chat_query.value(4).toInt();

                qDebug()<<QString("chatid=%1    passwd=%2     name=%3       email=%4    history=%5").arg(usr_id).arg(usr_passwd).arg(usr_name).arg(usr_email).arg(usr_history);
                ui->name->setText(usr_name);
            }
        }
        qDebug()<<port;
        senderAno = new QUdpSocket(this);
        receiver = new QUdpSocket(this);
        receiver->bind(port, QUdpSocket::ShareAddress);
        connect(receiver, &QUdpSocket::readyRead, this, &ChatWindow::processPendingDatagram);

        ui->pushButton->setShortcut(tr("ctrl+return"));
        ui->pushButton_3->setShortcut(tr("alt+c"));
        ui->pushButton_8->setShortcut(tr("ctrl+s"));
    }
}

ChatWindow::~ChatWindow()
{
    delete ui;
}

void ChatWindow::processPendingDatagram()
{
    //中文支持
//    QTextCodec *codec = QTextCodec::codecForName("GBK");
    // 拥有等待的数据报
    while(receiver->hasPendingDatagrams())
    {
        QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间
        QString str = time.toString("yyyy-MM-dd hh:mm:ss ddd"); //设置显示格式
        QByteArray datagram;

        // 让datagram的大小为等待处理的数据报的大小，这样才能接收到完整的数据
        datagram.resize(receiver->pendingDatagramSize());

        // 接收数据报，将其存放到datagram中
        receiver->readDatagram(datagram.data(), datagram.size());
        //ui->label->setText(datagram);
        ui->listWidget->addItem(str);
        chat += str+"\n";
        qDebug()<<datagram<<QString::fromLocal8Bit(datagram);
        ui->listWidget->addItem(usr_name+":"+QString::fromLocal8Bit(datagram));
        chat += usr_name+":"+datagram+"\n";
    }
}

void ChatWindow::pushButton_clicked()
{
    //中文支持
//    QTextCodec *codec = QTextCodec::codecForName("GBK");
    QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间
    QString str = time.toString("yyyy-MM-dd hh:mm:ss ddd"); //设置显示格式
    int port = LoginWidget::ID+8000;
    qDebug()<<port;
    QByteArray datagram = ui->textEdit->toPlainText().toUtf8();

    senderAno->writeDatagram(datagram.data(), datagram.size(),
                          QHostAddress("127.0.0.1"), port);
    ui->listWidget->addItem(str);
    chat += str+"\n";
    qDebug()<<ui->textEdit->toPlainText()<<QString::fromLocal8Bit(ui->textEdit->toPlainText().toUtf8());
    ui->listWidget->addItem("me:"+ui->textEdit->toPlainText());
    chat += "me:"+ui->textEdit->toPlainText()+"\n";
    this->ui->textEdit->clear();
    this->ui->textEdit->setFocus();
}

void ChatWindow::on_pushButton_3_clicked()
{
    this->close();
}

void ChatWindow::on_pushButton_8_clicked()
{
     /*
     * 通过QFile实现数据操作
     */
    qDebug()<<tr("Save File");
    qDebug()<<chat;
    QFile file("/Users/apple/Documents/QT/ChatLog.txt");
    // 以只写方式打开，如果文件不存在，那么会创建该文件
    if (!file.open(QIODevice::WriteOnly  | QIODevice::Text))
        qDebug() << file.errorString();
    file.write(chat);
    file.close();
    QMessageBox::information(this, QString::fromLocal8Bit("提示"), QStringLiteral("聊天记录保存成功！"));
}
